import { useParams } from 'react-router-dom';
import { Grid, Stepper, Toast } from 'antd-mobile';
import { SetStateAction, useEffect, useState } from 'react';
// import { useUserContext } from '@/hooks/userHooks';
// import { DISABLE_DEV } from '@/utils/constants';
import axios from 'axios';
import WxPay from '../../components/WxPay';
// import { useGetProductInfo } from '@/services/product';
// import { uniqueId } from 'lodash';
import style from './index.module.less';
import FailResult from './components/FailResult';
import SuccessResult from './components/SuccessResult';
// import { useGoTo } from "@/hooks";
// import { ROUTE_KEY } from "@/routes/menu";
import { useWxpayConfig } from '../../services/order';
import Hr from '@/components/Hr';
const WeixinJSBridge = (window as any).WeixinJSBridge;

/**
 * 购买商品信息
 */
const Buy = () => {
  // const { go } = useGoTo();
  // 当前商品ID
  const { productId = '' } = useParams();
  // 初始化购买页面state
  const [data, setdata] = useState({
    id: '1',
    preferentialPrice: 200,
    org: {
      name: '英语体验课 322 节',
      logo: 'https://water-drop-assets.oss-cn-hangzhou.aliyuncs.com/images/rc-upload-1683222801628-41.jpg',
    },
    name: '学乐英语（天安门店）',
    desc: '英语体验课 3 节',
    originalPrice: 500,
    logo: '',
  });
  // 获取商品详情信息
  const getlist = async () => {
    const courseDataileData = await axios.get(
      `http://localhost:3000/courseDetaile?id=${productId}`,
    );
    courseDataileData.data.data?.forEach((item : SetStateAction<{ id: string; preferentialPrice: number; org: { name: string; logo: string; }; name: string; desc: string; originalPrice: number; logo: string; }>) => {
      setdata(item);
    });
  };
  useEffect(() => {
    getlist();
  }, []);
  // const { data } = useGetProductInfo(id);
  const [count, setCount] = useState<number>(1);
  const [showResult, setShowResult] = useState({
    showSuccess: false,
    showFail: false,
  });
  // const { store, setStore } = useUserContext();
  const store = JSON.parse(localStorage.getItem('Student') || 'null')[0];
  const getWxConfig = useWxpayConfig();

  const [openPay, setOpenPay] = useState<boolean>(false);

  const buyHandler = async () => {
    // 调试状态下，直接吊起模拟微信支付
    // if (DISABLE_DEV) {
    //   setStore({
    //     ...store,
    //     // openid: uniqueId(),
    //     openid: 1,
    //   });
    //   setOpenPay(true);
    //   return;
    // }

    if (!store.openid) {
      window.location.href = `http://www.coderzsc.top/nest/wx/login?userId=${store.id}&url=${window.location.href}`;
      return;
    }

    if (!data || !productId) {
      Toast.show({
        content: '没有获取到商品信息',
      });
      return;
    }

    if (typeof WeixinJSBridge !== 'undefined') {
      const wxConfig = await getWxConfig(
        productId,
        count,
        data.preferentialPrice * count,
      );
      console.log(wxConfig, 'wxConfig--------------------------------');
      WeixinJSBridge.invoke(
        'getBrandWCPayRequest',
        {
          ...wxConfig,
        },
        (res: { err_msg: string }) => {
          if (res.err_msg === 'get_brand_wcpay_request:ok') {
            // 使用以上方式判断前端返回,微信团队郑重提示：
            // res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
            setShowResult({
              showSuccess: true,
              showFail: false,
            });
            return;
          }
          setShowResult({
            showSuccess: false,
            showFail: true,
          });
        },
      );
    } else {
      Toast.show({
        content: '请在微信中打开该页面',
      });
    }
  };

  // if (typeof WeixinJSBridge !== "undefined") {
  //   console.log("111111111111111111111111");
  //   getWxConfig(id,count, data.preferentialPrice * count);
  //   WeixinJSBridge.invoke(
  //     "getBrandWCPayRequest",
  //     {
  //       appId: "wx171385412597a59e", //公众号ID，由商户传入
  //       timeStamp: "1395712654", //时间戳，自1970年以来的秒数
  //       nonceStr: "e61463f8efa94090b1f366cccfbbb444", //随机串
  //       package: "prepay_id=up_wx21201855730335ac86f8c43d1889123400",
  //       signType: "RSA", //微信签名方式：
  //       paySign:
  //         "oR9d8PuhnIc+YZ8cBHFCwfgpaK9gd7vaRvkYD7rthRAZ/X+QBhcCYL21N7cHCTUxbQ+EAt6Uy+lwSN22f5YZvI45MLko8Pfso0jm46v5hqcVwrk6uddkGuT+Cdvu4WBqDzaDjnNa5UK3GfE1Wfl2gHxIIY5lLdUgWFts17D4WuolLLkiFZV+JSHMvH7eaLdT9N5GBovBwu5yYKUR7skR8Fu+LozcSqQixnlEZUfyE55feLOQTUYzLmR9pNtPbPsu6WVhbNHMS3Ss2+AehHvz+n64GDmXxbX++IOBvm2olHu3PsOUGRwhudhVf7UcGcunXt8cqNjKNqZLhLw4jq/xDg==", //微信签名
  //     },
  //     (res: { err_msg: string }) => {
  //       if (res.err_msg === "get_brand_wcpay_request:ok") {
  //         // 使用以上方式判断前端返回,微信团队郑重提示：
  //         //res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
  //       }
  //     }
  //   );
  // }

  const onWxpayCloseHandler = () => {
    setOpenPay(false);
  };

  const onFinishHandler = () => {
    setShowResult({
      showSuccess: true,
      showFail: false,
    });
  };
  // const list = JSON.parse(localStorage.getItem("Student"))[0];
  // const [url, setUrl] = useState(window.location.href);
  // const shouquan = async() => {
  //   const data1 = await axios.get(
  //     `http://localhost:3000/wxlogin?id=${list.id}&url=${window.location.href}`
  //   );
  //   console.log(data1.data.path,'data1.data.path');
  //   window.location.href = data1.data.path;
  // };
  if (!data) {
    return null;
  }
  if (showResult.showFail) {
    return (
      <FailResult price={data.preferentialPrice * count} orgName={data?.name} />
    );
  }
  if (showResult.showSuccess) {
    return (
      <SuccessResult
        price={data?.preferentialPrice * count}
        orgName={data?.name}
        productName={data?.name}
        productDesc={data?.desc}
      />
    );
  }
  return (
    <div className={style.container}>
      <WxPay
        visible={openPay}
        onClose={onWxpayCloseHandler}
        amount={data?.preferentialPrice * count}
        onFinish={onFinishHandler}
        productId={productId}
        quantity={count}
      />
      <div className={style.organization}>
        <div className={style.logo}>
          <img alt="" src={data?.logo} className={style.logoImg} />
        </div>
        <div className={style.orgName}>{data?.name}</div>
      </div>
      {/* <Hr /> */}
      <div className={style.title}>{data?.name}</div>
      <div className={style.desc}>{data?.desc}</div>
      {/* <Hr /> */}
      <div className={style.count}>
        购买数量
        <Stepper
          className={style.step}
          min={1}
          value={count}
          onChange={(value) => {
            setCount(value);
          }}
        />
      </div>
      <div className={style.price}>
        小计: ￥
        {data?.preferentialPrice * count}
        <span className={style.originalPrice}>
          ￥
          {data?.originalPrice * count}
        </span>
      </div>
      <Hr />
      <div className={style.user}>
        <span className={style.telLabel}>手机号</span>
        <span className={style.tel}>{store.tel}</span>
      </div>
      <Grid columns={2} className={style.buyContainer}>
        <Grid.Item span={1}>
          <span className={style.preferentialPrice}>
            ￥
            {data?.preferentialPrice * count}
          </span>
          <span className={style.originalPrice}>
            ￥
            {data?.originalPrice * count}
          </span>
        </Grid.Item>
        <Grid.Item
          span={1}
          className={style.buyButton}
          onClick={buyHandler}
        >
          {store.openid ? '提交订单' : '去微信授权'}
        </Grid.Item>
      </Grid>
    </div>
  );
};
export default Buy;
